﻿using System.Web.Mvc;
using SlamCms.Data;
using SlamCms.Web;
using SlamCmsDemo.Data;
using SlamCmsDemo.Web.Core;
using SlamCmsDemo.Web.Core.Models;

namespace SlamCmsDemo.HtmlCss.Controllers
{
	public class KnowledgeCenterController : Controller
	{
		private readonly SlamCmsContext slamCmsContext;

		public KnowledgeCenterController(SlamCmsContext slamCmsContext)
		{
			this.slamCmsContext = slamCmsContext;
		}

		[HttpGet]
		public ActionResult Index(TagBrowserParameters parameters)
		{
			// get the content items for the filtered tags
			var contentItems = slamCmsContext.CreateQuery(QueryBuilderOptions.AllZones)
											 .IncludeTags()
											 .FilterContentTypes<Article, Download, Faq>()
											 .FilterTaggedWithAll(parameters.FilteredTags)
											 .OrderByFeaturedOnTag(parameters.LastFilteredTag)
											 .Get();

			// build the tagtree for the current parameters
			var tagTree = slamCmsContext.GetTagTree()
										.ForTagBrowser(this, parameters)
										.RemoveHiddenTagsForTagMenu()
										.UpdateContentItemCount(contentItems)
										.RemoveTagsWithNoItems()
										.RemoveTagCategoriesWithNoTags();

			// now prepare the current page
			var pageContentItems = contentItems.GetPage(parameters.PageNumber, 15);

			// build the view model
			var model = new KnowledgeCenterIndexViewModel();
			model.TagTree = tagTree;
			model.Items = pageContentItems.ToContentList("Results");
			model.Pager = pageContentItems.ToPager(page => Url.TagBrowser(parameters).Page(page).Render());
			ViewData.Model = model;

		    return View();
		}
	}
}